package com.power.sifa.approve.dao.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.plf.common.domain.PageDataResponse;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.approve.dao.Apl_typical_caseDaoCustom;
import com.power.sifa.approve.model.enumeration.St_apply;
import com.power.sifa.approve.model.pojo.vo.TypicalCaseVO;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;


/**
 * 典型案件收藏表 持久层实现(hibernate)
 */

@Slf4j
@Repository
public class Apl_typical_caseDaoImpl implements Apl_typical_caseDaoCustom {

    @Resource
    private EntityManager entityManager;

    @Override
    public PageDataResponse pageTypicalCase(Pageable pageable) {
        StringBuffer sql = new StringBuffer("select c.applyid, c.acceptcode, m.status, c.applyname, c.targetname, " +
                "m.matid as servicename, m.instid from apl_typical_case c join apl_main m on c.applyid = m.id " +
                "where m.matid = '100000_360100-000201009000-QT-002-02'");

        // 创建查询并设置返回类型
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);

        int total = query.getResultList().size();
        if (total == 0) {
            return null;
        }

        // 应用分页设置
        int pageStart = pageable.getPageNumber() * pageable.getPageSize();
        List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageable.getPageSize()).getResultList();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<TypicalCaseVO> result = null;
        for (Map map : list) {
            map.put("servicename", "行政复议");
            Integer status = (Integer) map.get("status");
            map.put("status_text", St_apply.getName(status));
            map.put("links", St_apply.judge(status));
            result = JSON.parseArray(JSON.toJSONString(list), TypicalCaseVO.class);
        }

        return new PageDataResponse(result, Long.valueOf(total),
                pageable.getPageSize(), pageable.getPageNumber() <= 1 ? 1 : pageable.getPageNumber());
    }
}